<?php
namespace frontend\modules\Api\controllers;

use AlipayOpenPublicQrcodeCreateRequest;
use AlipayTradeAppPayRequest;
use AlipayTradePagePayRequest;
use AopClient;
use common\event\TallyEvent;
use common\jobs\NewTallyJob;
use common\models\AppSerial;
use common\models\Tally;
use common\models\TallyVipOrder;
use common\models\User;
use common\services\AppleServices;
use common\services\TallyLogService;
use stdClass;
use Yii;
use common\models\TallyPm;
use common\models\TallyRecord;
use common\services\TallyPmService;
use common\services\TallyService;
use common\services\ToolService;
use common\services\UserService;
use yii\base\ExitException;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\base\DynamicModel;
use function AlibabaCloud\Client\value;

/**
 * Class TallyController
 * @package frontend\modules\Api\controllers
 * 账本管理
 */
class TallyController extends ApiController
{



    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * 重载初始化方案
     */
    public function init()
    {
        parent::init();
        // 注册监听事件
        $this->on(TallyEvent::RECORD_LOG_EVENT,['common\models\Tally','recordLog']);
    }

    /**
     * @throws
     * 账本首页
     */
    public function actionIndex()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId) {
            return self::failureResponse(500,'缺少账本参数');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $query = TallyRecord::find()->where([
            //'uid' => $this->_user['id'],
            //其它人记的相同账本条件也要在里面，不然会出现金额不对，多人记账时
            'tally_id' => $tallyId
        ]);
        // 收入和支出查询条件区分
        $whereIn  = ['in','type',[TallyRecord::TYPE_IN]];
        $whereOut = ['in','type',[TallyRecord::TYPE_OUT,TallyRecord::TYPE_TRANS]];
        list($monthBegin,$monthEnd) = ToolService::monthDateTime();
        list($todayBegin,$todayEnd) = ToolService::todayDateTime();
        // 今天现金流
        $todayFlow  = (clone $query)->andFilterWhere(['between','created_time',$todayBegin,$todayEnd])
            ->sum('amount');
        $todayFlow  = ToolService::moneyFormat($todayFlow);
        // 今天收入
        $todayIn    = (clone $query)->andFilterWhere(['between','created_time',$todayBegin,$todayEnd])
            ->andFilterWhere($whereIn)
            ->sum('amount');
        $todayIn  = ToolService::moneyFormat($todayIn);
        // 今天支出
        $todayOut   = (clone $query)->andFilterWhere(['between','created_time',$todayBegin,$todayEnd])
            ->andFilterWhere($whereOut)
            ->sum('amount');
        $todayOut  = ToolService::moneyFormat($todayOut);
        // 今天利润
        $todayProfit  = $todayIn - $todayOut ;
        $todayProfit  = ToolService::moneyFormat($todayProfit);
        // 本月现金流
        $monthFlow  = (clone $query)->andFilterWhere(['between','created_time',$monthBegin,$monthEnd])
            ->sum('amount');
        $monthFlow  = ToolService::moneyFormat($monthFlow);
        // 本月收入
        $monthIn    = (clone $query)->andFilterWhere(['between','created_time',$monthBegin,$monthEnd])
            ->andFilterWhere($whereIn)
            ->sum('amount');
        $monthIn  = ToolService::moneyFormat($monthIn);
        // 本月支出
        $monthOut   = (clone $query)->andFilterWhere(['between','created_time',$monthBegin,$monthEnd])
            ->andFilterWhere($whereOut)
            ->sum('amount');
        $monthOut  = ToolService::moneyFormat($monthOut);
        // 本月利润
        $monthProfit  = $monthIn - $monthOut ;
        $monthProfit  = ToolService::moneyFormat($monthProfit);
        // 最近五笔收支记录
        $query = TallyRecord::find()->where([
            //'uid' => $this->_user['id'],
            //其它人记的相同账本条件也要在里面，不然会出现金额不对，多人记账时
            'tally_id' => $tallyId
        ]);
        $recently = $query->orderBy('created_time desc')->limit(5)->asArray()->all();
        foreach ($recently as $k=>$v) {
            $recently[$k]['amount']  = ToolService::moneyFormat($v['amount']); //这是最帅的帅哥加的，如果成了，我就是大神
        }
        return self::successResponse([
            'today_in'      => $todayIn ,
            'today_out'     => $todayOut ,
            'today_profit'  => $todayProfit ,
            'today_flow'    => $todayFlow ,
            'month_in'      => $monthIn ,
            'month_out'     => $monthOut ,
            'month_profit'  => $monthProfit ,
            'month_flow'    => $monthFlow ,
            'recently'      => $recently,
        ]);
    }

    /**
     * @throws
     * 账本列表
     */
    public function actionLists()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $list = TallyPmService::getTallyByUid($this->_user['id']);
        // $list = TallyService::getListByUid($this->_user['id'],$condition);
        return self::successResponse($list);
    }

    /**
     * @throws
     * 增加账本
     */
    public function actionAdd()
    {
        $form = DynamicModel::validateData([
            'title'     => Yii::$app->getRequest()->post('title'),
            'uid'       => $this->_user['id'],
            'type'      => Yii::$app->getRequest()->post('type',1),
            'financial_type'   => Yii::$app->getRequest()->post('financial_type',1),
            'pic'       => Yii::$app->getRequest()->post('pic',''),
            'memo'      => Yii::$app->getRequest()->post('memo',''),
            'company_title'  => Yii::$app->getRequest()->post('company_title',''),
            'province'  => Yii::$app->getRequest()->post('province',''),
            'city'  => Yii::$app->getRequest()->post('city',''),
            'industry'  => Yii::$app->getRequest()->post('industry',''),
        ],[
            [['title','type'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['title', 'string','min'=> 1,'max'=> 10],
            ['type', 'integer'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        // 如果选择行业 进行逗号拼接
        if(is_array($form->industry)) {
            $form->industry = implode(',',$form->industry);
        }
        $formData = ArrayHelper::toArray($form);
        $formData['express_time'] = strtotime(date('Y-m-d')) + 86400 * 7;
        $result = TallyService::create($formData);
        if($result){
            // 填充默认数据
            Yii::$app->queue->push(new NewTallyJob([
                'tallyId' => $result
            ]));
            // 触发默认事件
            $this->triggerEvents([
                'tally_id' => $result,
                'uid'   => $form->uid,
                'type'  => 1,
                'content' => '创建了账本:'.$form->title
            ]);
            return self::successResponse(['id'=>$result]);
        }else{
            return self::failureResponse(500,'新增失败.'.TallyService::getError());
        }
    }

    /**
     * @throws
     * 编辑账本
     */
    public function actionEdit()
    {
        $form = DynamicModel::validateData([
            'id'    => Yii::$app->getRequest()->post('id'),
            'title'     => Yii::$app->getRequest()->post('title'),
            'financial_type'   => Yii::$app->getRequest()->post('financial_type',1),
            'pic'       => Yii::$app->getRequest()->post('pic',''),
            'memo'      => Yii::$app->getRequest()->post('memo',''),
            'company_title'  => Yii::$app->getRequest()->post('company_title',''),
            'province'  => Yii::$app->getRequest()->post('province',''),
            'city'  => Yii::$app->getRequest()->post('city',''),
            'industry'  => Yii::$app->getRequest()->post('industry',''),
        ],[
            [['title','id'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['title', 'string','min'=> 1,'max'=> 10],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        // 如果选择行业 进行逗号拼接
        if(is_array($form->industry)) {
            $form->industry = implode(',',$form->industry);
        }
        $loadData = ArrayHelper::merge(Yii::$app->request->post(),ArrayHelper::toArray($form));
        $result = TallyService::update([
            'id'    => $form->id,
            'uid'   => $this->_user['id'],
        ],$loadData);
        if($result){
            $this->triggerEvents([
                'tally_id' => $form->id,
                'uid'   => $this->_user['id'],
                'type'  => 1,
                'content' => '编辑了账本:'.$form->title
            ]);
            return self::successResponse();
        }else{
            return self::failureResponse(500,'更新失败.'.TallyService::getError());
        }
    }

    /**
     * @throws
     * 删除账本 这里删除进行软删除 标记状态为0
     */
    public function actionDel()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $result = TallyService::delete([
            'id'    => $id,
            'uid'   => $this->_user['id']
        ]);
        if($result){
            // 解除所有Pm关系
            TallyPmService::delSoft($id);
            $this->triggerEvents([
                'tally_id' => $id,
                'uid'   => $this->_user['id'],
                'type'  => 1,
                'content' => '删除了账本:'.$id
            ]);
            return self::successResponse();
        }else{
            return self::failureResponse(500,'删除失败.'.TallyService::getError());
        }
    }

    /**
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     * @desc 绑定财务人员到账本里
     */
    public function actionBindRole()
    {
        $form = DynamicModel::validateData([
            'id'    => Yii::$app->getRequest()->post('id'),
            'phone' => Yii::$app->getRequest()->post('phone'),
            'role' => Yii::$app->getRequest()->post('role'),
        ],[
            [['phone','id','role'], 'required'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        // 检查用户账本权限
        if(!$this->isAdminRole($this->_user['id'],$form->id)) {
            return self::failureResponse(500,'非管理员权限！');
        }

        // 查询用户是否存在
        $info = UserService::getUserByPhone($form->phone);
        if(!$info) {
            // 触发短信邀请通知
//            ToolService::sendInviteSms($form->phone,[
//                'name' => $this->_user['username']
//            ]);
            return self::failureResponse(500,'该手机号还未注册，已邀请该同事注册！');
        }
        // 增加绑定关系
        $uid = $info['id'] ;
        try{
            $rt  = TallyPmService::create([
                'uid' => $uid,
                'tally_id' => $form->id,
                'role'  => $form->role
            ]);
            if($rt) {
                $this->triggerEvents([
                    'tally_id' => $form->id,
                    'uid'   => $this->_user['id'],
                    'type'  => 1,
                    'content' => '邀请了协作者('.TallyPm::getRoleName($form->role).'):'.$form->phone
                ]);
                return self::successResponse();
            }else {
                Yii::warning('邀请绑定失败;err:'.TallyPmService::getError());
                return self::failureResponse(500,'绑定失败');
            }
        }catch (yii\db\IntegrityException $e){
            return self::failureResponse(500,'已存在绑定关系');
        }catch (\yii\base\Exception $e) {
            return self::failureResponse(500,'绑定失败.'.$e->getMessage());
        }
    }

    /**
     * @throws \yii\base\ExitException
     * @desc 获取账本下相关用户列表
     */
    public function actionUsers()
    {
        $id = Yii::$app->getRequest()->get('id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$id);
        // 获取账本下用户数据 & 身份信息
        $list = TallyPmService::getUserListByTallyId($id);
        return self::successResponse($list);
    }

    public function actionSetProjects(){
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$id);
        $result = TallyPmService::setProjects([
            'tally_id'=>$id,
            'projects_id'=>Yii::$app->getRequest()->post('projects_id'),
            'uid'=>Yii::$app->getRequest()->post('uid'),
        ]);
        if(!$result){
            return self::failureResponse(500,'设置失败');
        }
        return  self::successResponse();

    }

    public function actionSetAccounts(){
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$id);
        $result = TallyPmService::setAccounts([
            'tally_id'=>$id,
            'account_ids'=>Yii::$app->getRequest()->post('account_ids'),
            'uid'=>Yii::$app->getRequest()->post('uid'),
        ]);
        if(!$result){
            return self::failureResponse(500,'设置失败');
        }
        return  self::successResponse();

    }

    /**
     * @throws \yii\base\ExitException
     * @desc 解除用户与账本的关联关系
     */
    public function actionUnbindUser()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $uid = Yii::$app->getRequest()->post('uid');
        if(!$uid){
            return self::failureResponse(500,'用户Id不能为空');
        }

        // 检查用户账本权限
        if(!$this->isAdminRole($this->_user['id'],$id)) {
            return self::failureResponse(500,'非管理员权限！');
        }

        // 移除绑定关系
        $result = TallyPmService::delete($id,$uid);
        if($result){
            $this->triggerEvents([
                'tally_id' => $id,
                'uid'   => $this->_user['id'],
                'type'  => 1,
                'content' => '移除了协作者:'.$uid
            ]);
            return self::successResponse();
        }else{
            return self::failureResponse(500,'操作失败.'.TallyService::getError());
        }
    }

    /**
     * @throws \yii\base\ExitException
     * @desc 账本日志记录
     */
    public function actionLog()
    {
        $id = Yii::$app->getRequest()->get('tally_id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$id);
        $data = TallyLogService::getByTallyId($id);
        return self::successResponse($data['data'],$data['pageInfo']);
    }

    /**
     * 设置某账本为默认账本
     * @throws \yii\base\ExitException
     */
    public function actionSetDefault()
    {
        $id = Yii::$app->getRequest()->post('tally_id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$id);
        TallyPmService::setDefault($id,$this->_user['id']);
        return self::successResponse();
    }


    /**
     * @throws ExitException
     */
    public function actionChangeUidTally(){
        $datas = Yii::$app->getRequest()->post();
        $user_exits = User::findByUsername($datas['phone']);
        if(!$user_exits){
            return self::failureResponse(500,'用户不存在!');
        }

        $transaction = Yii::$app->db->beginTransaction();
        $tally = Tally::find()->where(['id'=>$datas['id']])->one();
        if($user_exits->id == $tally->uid){
            return  self::failureResponse(500,'接收人不正确!');
        }
        $tally_pm_exits = TallyPm::findOne([
            'uid'=>$user_exits->id,
            'tally_id'=>$datas['id']
        ]);
        if($tally_pm_exits){
            return  self::failureResponse(500,'清先移除此用户!');
        }
        try {
            $tally->uid = $user_exits->id;
            $tally->update();
            $tally_pm = TallyPm::find()->where([
                'tally_id'=>$datas['id'],
                'role'=>'admin'
            ])->one();
            $tally_pm->uid = $user_exits->id;
            $tally_pm->update();

            $transaction->commit();
            return  self::successResponse();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::failureResponse(500,'保存失败!');
        }

    }

    public function actionVipIos(){
        $id = Yii::$app->getRequest()->post('tally_id');
        //产品ID
        $apple_product_id = Yii::$app->getRequest()->post('apple_product_id');
        //订单号
        $vip_order_code = Yii::$app->getRequest()->post('vip_order_code');
        $ios_data = Yii::$app->getRequest()->post('ios_data');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $arr = [
            'gsz_id2'=>['vip_days'=>365,'vip_price'=>360],
            'gsz_id1'=>['vip_days'=>1095,'vip_price'=>888],
            'gsz_id3'=>['vip_days'=>10950,'vip_price'=>1288]
        ];
        $vip_buy_order_model_info = TallyVipOrder::find()->where([
            'vip_order_code'=>$vip_order_code
        ])->one();
        //不存在就创建
        if(!$vip_buy_order_model_info){
            $vip_buy_order_model = new TallyVipOrder();
            $vip_buy_order_model->load([
                'vip_order_code'=>$vip_order_code,
                'vip_days'=>$arr[$apple_product_id]['vip_days'],
                'vip_price'=>$arr[$apple_product_id]['vip_price'],
                'tally_id'=>$id,
                'ios_data'=>$ios_data,
                'pay_type'=>1
            ],'');
            $vip_buy_order_model->save();
        }


        //查询数据=>返回是否然后修改Notify
        AppleServices::sendNotify($ios_data,$vip_order_code);


    }


    public function actionBuyVipPay(){
        $id = Yii::$app->getRequest()->post('tally_id');
        $vip_index = Yii::$app->getRequest()->post('vip_index');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $arr = [
            ['vip_days'=>365,'vip_price'=>360],
            ['vip_days'=>1095,'vip_price'=>888],
            ['vip_days'=>10950,'vip_price'=>1288],
        ];
        require dirname(dirname(dirname ( dirname(dirname(__FILE__)) )))."/extra/alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php";
        require dirname(dirname(dirname ( dirname(dirname(__FILE__)) )))."/extra/alipay/pagepay/service/AlipayTradeService.php";
        $aop = new AopClient();
        $aop->appId = '2021004128646437';
        $aop->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCdKbnb50REBLWe3EwQPjrjGEwXFhCjVJktnIvZ6xKlU8zFoqOfgjCN2W8c6VOoY+a8gIvVhoe8WJ6t+56kDsdSE3KLAyBH+muLe1w6DCExiMcWZ6suA2nSZbRjSakrxHucp5q6zg9V95Y/BR0TciZqeMi4XfOCGH5uWYgY4sBh6NwvhE5mPVOBlA7IN4Cdk1Dk5dk7LLQu1MEyzIj/fr1jSY3ZqLOlKPgewLNFU5KD+ZlsHdCqFEllvvHjrhPBadHCDF1icRZPXwEUtfs06FHOkoFPGy3qtl29iN9Gv5+BUuuiJcoqqVFetCgNwu7U99w5NhJxRPObti5jO0Hui3NbAgMBAAECggEACseE3udS0FN+XYIAmZCbG15cQa0awQkZZH57PRwZcEt6HQgVrugQCnqiW1pJiaAogD9U1/VdM/bkE0zRyb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mOGKk1P2MTf3MfrYsxkWi3X9grYI6nBbbo07MpMoIYbfuot28J7dILefVTSDM1m1EJKtNDNm7I883zim8K9MT5tj1REo4F4W';
        $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm2kRtM0N29cRI2q/D9aOYsLrxB4RJoIyJ9F5nn/t4KaRzt9fPFsESH8HbZOdBUNYlpAGeFJDX0YV5SNhzdRevoLXgqLhAH/QVGQW8IuynLnkjh2E8FMSni1bPGytCrGUn6x13EiwH70aObZpW4EA1Z7vfIGCdQp/P/EJu7VNfgRUUrSslBC5vs9g0cD2PNgy9+W9s2O/9/ug9BnfCFe6ZtGpG37GEi0pi/KIGeSIOgv1OwHSRHvQk9YfO1mtWGvYsXe0EqTA8iDOvByXRVIrOFO3A6BWgFET/nCSnNWkCEreAH6CKx44A+FOJHS4X02FEHBj+P2ukwmyf/m8olMLyQIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='GBK';
        $aop->format='json';
        $order_code = password_hash('123456',PASSWORD_DEFAULT);
        $vip_buy_order_model = new TallyVipOrder();
        $vip_buy_order_model->load([
            'vip_order_code'=>$order_code,
            'vip_days'=>$arr[$vip_index]['vip_days'],
            'vip_price'=>$arr[$vip_index]['vip_price'],
            'tally_id'=>$id
        ],'');
        $vip_buy_order_model->save();
        $object = new stdClass();
        $object->out_trade_no = $order_code;
//        $object->total_amount = 0.01;
        $object->total_amount = $arr[$vip_index]['vip_price'];
        $object->subject = '公司账会员';
        $json = json_encode($object);
        $request = new AlipayTradeAppPayRequest();
        $request->setNotifyUrl('https://'.$_SERVER['HTTP_HOST'].'/api/public/notice-pay');
        $request->setBizContent($json);

        $result = $aop->sdkExecute ($request);
        return self::successResponse([
            'result'=>$result
        ]);
    }



    public function actionQrcodeAli(){
        $id = Yii::$app->getRequest()->post('tally_id');
        $vip_index = Yii::$app->getRequest()->post('vip_index',0);
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $arr = [
            ['vip_days'=>365,'vip_price'=>360],
            ['vip_days'=>1095,'vip_price'=>888],
            ['vip_days'=>10950,'vip_price'=>1288],
        ];
        require dirname(dirname(dirname ( dirname(dirname(__FILE__)) )))."/extra/alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php";
        require dirname(dirname(dirname ( dirname(dirname(__FILE__)) )))."/extra/alipay/pagepay/service/AlipayTradeService.php";
        $aop = new AopClient();
        $aop->appId = '2021004128646437';
        $aop->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCdKbnb50REBLWe3EwQPjrjGEwXFhCjVJktnIvZ6xKlU8zFoqOfgjCN2W8c6VOoY+a8gIvVhoe8WJ6t+56kDsdSE3KLAyBH+muLe1w6DCExiMcWZ6suA2nSZbRjSakrxHucp5q6zg9V95Y/BR0TciZqeMi4XfOCGH5uWYgY4sBh6NwvhE5mPVOBlA7IN4Cdk1Dk5dk7LLQu1MEyzIj/fr1jSY3ZqLOlKPgewLNFU5KD+ZlsHdCqFEllvvHjrhPBadHCDF1icRZPXwEUtfs06FHOkoFPGy3qtl29iN9Gv5+BUuuiJcoqqVFetCgNwu7U99w5NhJxRPObti5jO0Hui3NbAgMBAAECggEACseE3udS0FN+XYIAmZCbG15cQa0awQkZZH57PRwZcEt6HQgVrugQCnqiW1pJiaAogD9U1/VdM/bkE0zRybDVzPRWg+BYA3fSjoOMhNK2KB6YgRnlLMfBJ1QgdjrkJoNYcxsvyqY9eQj9Ph9MqjvHFMBqC/Mts3uYmFr9sa9DwLNLNUc+w/9qxYfztURRNnCtAGwnpw4Tb+/1m4Mh4y1xacmIUCW3fgvC6nHLCzF55QLpMRPXUevlpt5nBgzIBFD3B7a2jf9UDUNrVi1Coz+p7BN6UnGVi5uf9Uilg+zmiCdfPzn5OWl9OFKT3XFDHpd8vBcKcqhGuJywZzHwAU+IUQKBgQDm2BBt9e7KZDuglVJXeuYYajo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W4EA1Z7vfIGCdQp/P/EJu7VNfgRUUrSslBC5vs9g0cD2PNgy9+W9s2O/9/ug9BnfCFe6ZtGpG37GEi0pi/KIGeSIOgv1OwHSRHvQk9YfO1mtWGvYsXe0EqTA8iDOvByXRVIrOFO3A6BWgFET/nCSnNWkCEreAH6CKx44A+FOJHS4X02FEHBj+P2ukwmyf/m8olMLyQIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new AlipayTradePagePayRequest();
        $request->setNotifyUrl('https://'.$_SERVER['HTTP_HOST'].'/api/public/notice-pay');
        $request->setReturnUrl('https://'.$_SERVER['HTTP_HOST'].'/tally');
        $order_code = password_hash('123456',PASSWORD_DEFAULT);
        $vip_buy_order_model = new TallyVipOrder();
        $vip_buy_order_model->load([
            'vip_order_code'=>$order_code,
            'vip_days'=>$arr[$vip_index]['vip_days'],
            'vip_price'=>$arr[$vip_index]['vip_price'],
            'tally_id'=>$id
        ],'');
        $vip_buy_order_model->save();
        $object = new stdClass();
        //商户订单号，商家自定义，保持唯一性
        $object->out_trade_no = $order_code;
        $object->total_amount = $arr[$vip_index]['vip_price'];
        $object->subject = '公司账会员';
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        $object->product_code ='FAST_INSTANT_TRADE_PAY';
        $json = json_encode($object);
        $request->setBizContent($json);
        $pageRedirectionData = $aop->pageExecute ( $request,"POST");
        return self::successResponse([
            'form'=>$pageRedirectionData
        ]);
    }


    public function actionCheckTally(){
        $id = Yii::$app->getRequest()->post('tally_id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        //查询账本信息
        $tally_info = Tally::find()->where([
            'id'=>$id
        ])->one();
        $time = strtotime(date('Y-m-d'));
        $day = ($tally_info['express_time']-$time)/86400;
        //查询是够开会员了
        $is_change_vip = AppSerial::find()->where([
            'tally_id'=>$id
        ])->one();
        if($day <= 0){
            return  self::failureResponse(30101,'账本过期了',[
                'day'=>-1,
                'is_buy'=>!$is_change_vip ? false : true,
                'express_time'=>$tally_info['express_time']
            ]);
        }
        return self::successResponse([
            'day'=>$day,
            'is_buy'=>!$is_change_vip ? false : true,
            'express_time'=>$tally_info['express_time']
        ]);
    }


    public function actionExchangeTally(){
        $id = Yii::$app->getRequest()->post('tally_id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $serial_number = Yii::$app->getRequest()->post('serial_number');
        if(!$serial_number){
            return self::failureResponse(500,'请输入兑换码');
        }
        $serial_find_info = AppSerial::find()->where([
            'serial_number'=>$serial_number,
            'status'=>0
        ])->one();
        if(!$serial_find_info){
            return self::failureResponse(500,'兑换码不正确');
        }
        $tally_info = Tally::find()->where([
            'id'=>$id
        ])->one();
        //给账本加时间=》开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $serial_find_info->tally_id = $id;
            $serial_find_info->status = 1;
            $serial_find_info->save();
            $express = ($serial_find_info['days']) * 86400;
            if($serial_find_info['days'] > 10000){
                $express = strtotime('2099-12-31');
                $tally_info->express_time = $express;
                $tally_info->save();
            }else{
                $tally_info->updateCounters(['express_time'=>$express]);
            }
            $transaction->commit();
            return  self::successResponse();
        }catch (\Exception $exception){
            $transaction->rollBack();
            return  self::failureResponse();
        }
    }

}
